package com.qf.controller;

import com.qf.pojo.Cart;
import com.qf.pojo.User;
import com.qf.service.CartService;
import com.qf.service.CartServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**  购物车管理
 * @author hanjiejie
 * @version V1.0
 * @Project java2203
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/5/26 14:15
 */
@WebServlet("/cart")
public class CartController  extends BaseServlet{
    /**
     * 创建购物车
     * @param request
     * @param response
     * @return
     */
    public String create(HttpServletRequest request, HttpServletResponse response){
        //获取商品ip
        String pid = request.getParameter("pid");
        //获取session会话中当前用户的id
        User user = (User) request.getSession().getAttribute("loginUser");
        if (user == null){
            return "redirect:/login.jsp";
        }
        //调用业务层将购物车存到数据库中
        CartService cartService = new CartServiceImpl();
        cartService.createCart(user.getId(), Integer.parseInt(pid));
        //跳转到购物车查询列表方法
        return "redirect:/cart?method=show";
    }

    /**
     * 查询指定用户的购物车数据 ，并跳转到购物车列表页面展示出来
     * @param request
     * @param response
     * @return
     */
    public  String show (HttpServletRequest request,HttpServletResponse response){
          //获取用户的id'
        User user = (User)request.getSession().getAttribute("loginUser");
        if (user == null){
            return "redirect:/login.jsp";
        }
        //根据id去业务层擦查找用户的购物车数据
        CartService cartService = new CartServiceImpl();
        List<Cart> cartList = cartService.findCartByUid(user.getId());

       //将用户购物车的数据放入request狱中，带到页面展示
        request.setAttribute("list", cartList);
        //4. 跳转到购物车列表页面展示
        return "forward:/cart.jsp";
        }


    }

